<template>
	<Tips/>
	<view class="vote_box_add">
		<view class="header">
			<MyNull height="calc(20vh)" img="createRandomLots.png"/>
			<TipInfo color="#FFFFFF" id="15"></TipInfo>
		</view>
		<view class="content_card">
			<view class="vote_title">
				<MyInput
					label="主题"
					v-model="fromData.title"
					:focus="false"
					fontSize="30rpx"
					height="50rpx"
					placeholder="点我输入主题(必填)"/>				
			</view>
			<view class="vote_line"></view>
			<view class="vote_title">
				<MyInput
					label="描述"
					v-model="fromData.desc"
					:focus="false"
					fontSize="30rpx"
					height="50rpx"
					placeholder="点我输入描述(选填)"/>					
			</view>
		</view>
		<view class="content_card">
			<view class="vote_title" @click="toggleImgWordVoteFun(fromData.type===VoteType.IMG_WORD ? true : false)">
				<view class="extra_title" style="margin-left: 5rpx;">
					图文投票			
				</view>
				<MySwitch :state="fromData.type===VoteType.IMG_WORD ? true : false"/>
			</view>
			<view class="vote_line"></view>
			<template v-for="id in Object.keys(fromData.votes)" :key="id">
				<view class="vote_title">
					<view class="content">
						<view @click="deleteVoteFun(id)" style="margin-right: 14rpx;">
							<MyIcons size="40rpx" :src="joinSystemPath('del_light.png')"/>
						</view>
						<MyInput
							:focus="false"
							inputWidth="100%"
							fontSize="30rpx"
							v-model="fromData.votes[id].name"
							placeholder="点我输入投票选项"
							height="50rpx"/>
					</view>
					<view v-if="fromData.type===VoteType.IMG_WORD" class="img_box" @click="fromData.votes[id].img ? ()=>{} : uploadVoteImg(id)">
						<view
							class="close_btn" 
							v-if="fromData.votes[id].img"
							@click.stop="deleteVoteImg(id)"
						>
							<MyIcons size="30rpx" :src="joinSystemPath('closeRed2.png')"/>
						</view>
						<template v-if="fromData.votes[id].img">
							<Avatar
								size="150rpx" 
								:isAllowPreview="fromData.votes[id].img ? true : false"
								radius="10rpx"
								:fileName="fromData.votes[id].img ? fromData.votes[id].img : 'addImg.png'" 
								:joinUrlFun="joinVoteImg"/>	
						</template>
						<template v-else>
							<view style="background-color: rgba(0, 0, 0, 0.05);width:150rpx;height:150rpx;display: flex;justify-content: center;align-items: center;">
								<Avatar
									size="100rpx" 
									:isAllowPreview="fromData.votes[id].img ? true : false"
									radius="10rpx"
									:fileName="fromData.votes[id].img ? fromData.votes[id].img : 'addImg.png'" 
									:joinUrlFun="joinVoteImg"/>	
							</view>
						</template>
					</view>
				</view>
				<view class="vote_line"></view>
			</template>
			<view class="vote_title">
				<view class="content" @click="addVoteFun()">
					<view style="margin-right: 14rpx;">
						<MyIcons size="40rpx" :src="joinSystemPath('add_light.png')"/>
					</view>
					<MyInput
						:focus="false"
						inputWidth="100%"
						fontSize="30rpx"
						v-model="addTip"
						:disabled="true"
						:color="primary_light_color"
						height="50rpx"/>
				</view>
				<view class="count_votes_nums">(共计{{Object.keys(fromData.votes).length}}个票)</view>
			</view>
		</view>
		<view class="content_card">
			<AdBanner width="100%" diyStyle="margin: -10rpx 0rpx 5rpx 0;"/>
			<view class="vote_title" @click="toggleMultVoteFun(fromData.isMult===VoteIsMult.IS_MULT ? true : false)">
					<view class="extra_title" style="margin-left: 5rpx;">
						多选投票			
					</view>
				<MySwitch :state="fromData.isMult===VoteIsMult.IS_MULT ? true : false"/>
			</view>
			<view class="vote_line"></view>
			<view class="vote_title" @click="toggleHiddenUserName(fromData.isHiddenUserName===VoteIsHiddenUserName.IS_HIDDEN ? true : false)">
				<view class="extra_title" style="margin-left: 5rpx;">
					匿名投票			
				</view>
				<MySwitch :state="fromData.isHiddenUserName===VoteIsHiddenUserName.IS_HIDDEN ? true : false"/>
			</view>
			<view class="vote_line"></view>
			<view class="vote_title" @click="toggleResultView(fromData.resultViewType===VoteResultView.OVER_VIEW ? true : false)">
				<view class="extra_title" style="margin-left: 5rpx;">
					{{fromData.resultViewType === VoteResultView.JOINED_VIEW ? '参与后可看票数' : '结束后可看票数'}}			
				</view>
				<MySwitch :pointTip="['换','换']" :state="fromData.resultViewType===VoteResultView.JOINED_VIEW ? true : false"/>
			</view>
			<view class="vote_line"></view>
			<view class="vote_title">
				<view class="extra_title" style="margin-left: 5rpx;">
					参与人数		
				</view>
				<uni-number-box v-model="fromData.limitJoinNums"/>
			</view>
		</view>
		<view class="submit_box">
			<MyButton :clickFun="submit" :bgc="primary_light_color">发布</MyButton>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app'
	import {computed, ref,onDeactivated,nextTick} from 'vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyNull from '@/components/MyNull/MyNull.vue'
	import TipInfo from '@/components/TipInfo/TipInfo.vue'
	import MySwitch from '@/components/MySwitch/MySwitch.vue'
	import MyIcons from '@/components/MyIcons/MyIcons.vue'
	import Avatar from '@/components/Avatar/Avatar.vue'
	import MyButton from '@/components/MyButton/MyButton.vue'
	import AdBanner from '@/components/AdBanner/AdBanner.vue'
	
	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	
	import {
		joinSystemPath,
		joinVoteImg
	} from '@/utils/imgJoinName.js'
	
	import {uploadImgHook} from '@/hooks/uploadImg.js'
	import {
		verifyIsLogin,
		verifyIsShowChooseAd
	} from '@/hooks/verify.js'
	
	import {dynamicStyleStore} from '@/stores/dynamicStyle.js'
	import {
		userStore
	} from '@/stores/user'
	
	import {
		VoteDataState,
		VoteIsMult,
		VoteIsHiddenUserName,
		VoteResultView,
		VoteType,
	} from '@/enum/GlobalEnum.js'
	
	const dynamicStyle_store = dynamicStyleStore()
	const dormitoryModel = new DormitoryModel()
	const user_store = userStore()
	
	const isPrivacy = computed(()=>user_store.userInfo.isPrivacy)
	
	const dormitoryId = ref(uni.getStorageSync('homeData').dormitory_id)
	
	const {
		primary_hot_color,
		primary_light_color,
		primary_main_bgc,
		primary_shallow_color,
		shallow_text_color,
		primary_text_color,
		cool_border_color
	} = dynamicStyle_store.dormitoryStyle
	
	const fromData = ref({
		title:'',
		desc:'',
		type:1,
		isMult:0,
		isHiddenUserName:0,
		resultViewType:1,
		limitJoinNums:3,
		votes:{
			0:{
				name:'',
				img:''
			},
			1:{
				name:'',
				img:''
			}
		}
	})
	const chooseVoteByUploadImg=ref('')
	const addTip = ref('添加一个投票项')
	
	const toggleImgWordVoteFun=(oldType)=>{
		fromData.value.type = oldType ? VoteType.WORD : VoteType.IMG_WORD
		const keys = Object.keys(fromData.value.votes)
		keys.forEach(id=>fromData.value.votes[id].img='')
	}
	const toggleMultVoteFun=(oldIsMult)=>{
		fromData.value.isMult = oldIsMult ? VoteIsMult.NO_MULT : VoteIsMult.IS_MULT
	}
	const toggleHiddenUserName=(oldHidden)=>{
		fromData.value.isHiddenUserName = oldHidden ? VoteIsHiddenUserName.NO_HIDDEN : VoteIsHiddenUserName.IS_HIDDEN
	}
	const toggleResultView=(oldResultView)=>{
		if(oldResultView){
			uni.$emit('tips','每个人参与后就能看到票数,创建者随时都可以看','info',3000)
		}else{
			uni.$emit('tips','所有人都参与后才能看到票数,创建者随时都可以看','info',3000)
		}
		fromData.value.resultViewType = oldResultView ? VoteResultView.JOINED_VIEW : VoteResultView.OVER_VIEW
	}
	const uploadVoteImg=(id)=>{
		console.log('点击')
		verifyIsLogin()
		uni.$emit('checkUserPrivacyProtocol')
		if(!isPrivacy.value){
		    return
		}
		chooseVoteByUploadImg.value = id
		uploadImgHook("uploadVoteImg",`/upload/vote/img`)
	}
	const deleteVoteImg=(id)=>{
		fromData.value.votes[id].img=''
	}
	const submit=async()=>{
		verifyIsLogin()
		if(!fromData.value.title.trim()){
			uni.$emit('tips','主题不能为空','warn')
			return
		}
		const keys = Object.keys(fromData.value.votes)
		const arr=[]
		const names=[]
		keys.forEach((item,index)=>{
			const obj = fromData.value.votes[item]
			if(!obj.name.trim()){
				const err = `请输入第${index+1}票的名字`
				uni.$emit('tips',err,'warn')
				throw new Error(err)
			}
			if(fromData.value.type===VoteType.IMG_WORD){
				if(!obj.img){
					const err = `请上传第${index+1}票的图片`
					uni.$emit('tips',err,'warn')
					throw new Error(err)
				}
			}
			names.push(obj.name.trim())
			obj.id=index
			arr.push(obj)
		})
		if([...(new Set(names))].length!==arr.length){
			uni.$emit('tips','名字不能有重复的','warn')
			return
		}
		if(fromData.value.limitJoinNums<2 || fromData.value.limitJoinNums > 200){
			uni.$emit('tips','参与人数最低两人,最多100人','warn')
			return
		}
		verifyIsShowChooseAd(getCurrentPages(),'创建投票')
		const {data,success}=await dormitoryModel.postAddVote({
			...fromData.value,
			votes:arr
		},dormitoryId.value)
		if(success){
			uni.$emit('tips','创建成功，正在跳转','success')
			setTimeout(()=>{
				uni.redirectTo({
					url:`/pages/Dormitory/VoteInfo/VoteInfo?id=${data}&isNew=true`
				})				
			},500)
		}
	}
	const deleteVoteFun=(id)=>{
		const _votes = JSON.parse(JSON.stringify(fromData.value.votes))
		const keys = Object.keys(_votes)
		if(keys.length <= 2){
			uni.$emit('tips','最少保留两个票项','warn')
			return
		}
		delete _votes[id]
		fromData.value.votes = _votes
	}
	const handleCopy=async(id)=>{
		const {data,success} = await dormitoryModel.getVoteInfo({},id)
		if(success){
			const tmp = {
				title:data.title,
				desc:data.voteDesc,
				type:data.type,
				isMult:data.isMult,
				isHiddenUserName:data.isHiddenUserName,
				resultViewType:data.resultViewType,
				limitJoinNums:data.limitJoinNums,
			}
			const votesTmp = {}
			data.joinContent.forEach(item=>{
				votesTmp[item.id] = {
					name:item.name,
					img:item.img
				}
			})
			tmp.votes = votesTmp
			fromData.value = tmp
		}
	}
	//监听图片上传成功
	uni.$on('uploadVoteImg',function(data){
		;(()=>{
			if(data){
				fromData.value.votes[chooseVoteByUploadImg.value].img = data
			}
		})()
	})
	
	//添加
	const addVoteFun=()=>{
		const _votes = JSON.parse(JSON.stringify(fromData.value.votes))
		const keys = Object.keys(_votes).map(item=>Number(item))
		if(keys.length===100){
			uni.$emit('tips','最多添加100种票','warn')
			return
		}
		//从大到小排序
		keys.sort((a,b)=>b-a)
		_votes[keys[0]+1] = {
			name:'',
			img:''
		}
		fromData.value.votes = _votes
	}
	
	//获取宿舍成员
	const getUsers=async()=>{
		const {
			data,
			success
		} = await dormitoryModel.getAllJoiner({
			limit:1000,
			page: 0,
			orderBy: 'createAt.asc'
		}, dormitoryId.value)
		if(success){
			fromData.value.limitJoinNums=data.length
		}
	}
	onLoad((opt)=>{
		const {id} = opt
		if(id){
			handleCopy(id)
		}else{
			getUsers()
		}
		nextTick(()=>{
			uni.$emit('checkUserPrivacyProtocol')
		})
	})
	onDeactivated(()=>{
		uni.$off('uploadBillProof')
	})
</script>

<style lang="less">
	.vote_line{
		width: 100%;
		height: 1rpx;
		background-color: v-bind(cool_border_color);
		margin: 10rpx 0;
	}
	.extra_title{
		color: v-bind(primary_text_color);
	}
	.vote_box_add{
		background-image: linear-gradient(to top, rgba(97,214,213,0),rgba(97,214,213,1));
		height: calc(100vh);
		.submit_box{
			padding: 20rpx;
			padding-bottom: 40rpx;
		}
		.header{
			display: grid;
			grid-template-columns: 3fr 2fr;
			align-items: center;
		}
		.content_card{
			background-color: #FFFFFF;
			margin: 0 20rpx;
			border-radius:20rpx 20rpx;
			padding: 10rpx;
			margin-bottom: 20rpx;
			.img_box{
				background-color: v-bind(primary_main_bgc);
				width: 150rpx;
				height: 150rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 10rpx;
				position: relative;
				margin-top: 10rpx;
				.close_btn{
					position: absolute;
					top: -16rpx;
					left: -20rpx;
				}
			}
			.vote_title{
				padding: 5rpx 10rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.content{
					display: flex;
					margin-left: -5rpx;
				}
				.count_votes_nums{
					color: v-bind(primary_text_color);
					font-size: 24rpx;
					text-align: end;
					width: 300rpx;
				}
			}
		}
		.content_card:nth-last-child(1){
			border-radius:20rpx 20rpx 0 0;
		}
	}
</style>
